﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using ThresholdAssistant.Attributes.Models;
using ThresholdAssistant.Autofac;
using ThresholdAssistant.ConfigSdk;
using ThresholdAssistant.DataContract.Result;
using ThresholdAssistant.Enums;
using ThresholdAssistant.Http;
using ThresholdAssistant.NLogSdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace ThresholdAssistant.Attributes
{
    /// <summary>
    /// 商户授权控制器
    /// </summary>
    public class MerchantAuthAttribute : Attribute, IAsyncAuthorizationFilter
    {
        /// <summary>
        /// 是否必填(默认：true)
        /// </summary>
        public bool Required { get; set; } = true;

        /// <summary>
        /// 商户编号Key名称
        /// </summary>
        public static readonly string merchantNoKey = "merchantNo";

        /// <summary>
        /// 授权处理方法
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            var result = new ContractResult();
            try
            {
                if (!Required)
                {
                    result.SetSuceccful();
                    return;
                }
                var headers = context.HttpContext.Request.Headers;
                if (!headers.ContainsKey(merchantNoKey))
                {
                    //提示请输入商户号
                    result.SetError(ErrorTypeEnum.MerchantRequired);
                    return;
                }

                var merchantResult = await GetMerchantTicket(context.HttpContext);
                if (!merchantResult.IsSuceccful())
                {
                    result.ErrorCode = merchantResult.ErrorCode;
                    result.ErrorMessage = merchantResult.ErrorMessage;
                    return;
                }

                var merchantInfo = merchantResult.Data;
                if (merchantInfo.Status != MerchantStatusEnum.Normal)
                {
                    //商户状态未启用，暂无权限
                    result.SetError(ErrorTypeEnum.MerchantStatusNoEnable);
                    return;
                }
                result.SetSuceccful();
            }
            catch (Exception ex)
            {
                NLogUtil.Error($"【商户授权】发生未经处理的异常：{ex}");
            }
            finally
            {
                if (!result.IsSuceccful())
                {
                    context.Result = new JsonResult(result);
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
                }
            }
        }

        /// <summary>
        /// 获取商户信息
        /// </summary>
        /// <param name="context">Http上下文</param>
        /// <returns></returns>
        public static MerchantModel GetMerchantInfo(HttpContext context)
        {
            var merchantResult = GetMerchantTicket(context).Result;
            if (!merchantResult.IsSuceccful())
                return null;

            return merchantResult.Data;
        }

        /// <summary>
        /// 获取商户信息
        /// </summary>
        /// <param name="context">Http上下文</param>
        /// <returns></returns>
        public static async Task<ContractResult<MerchantModel>> GetMerchantTicket(HttpContext context)
        {
            var result = new ContractResult<MerchantModel>();
            var headers = context.Request.Headers;
            if (!headers.ContainsKey(merchantNoKey))
            {
                return result.SetError(ErrorTypeEnum.MerchantRequired);
            }

            var merchantNoString = $"{headers[merchantNoKey]}";
            var merchantNo = merchantNoString.Split(',').FirstOrDefault();
            var httpClient = AutofacProvider.GetService<HttpClientUtil>();
            var paramsDic = new Dictionary<string, string>() { { "merchantNo", merchantNo } };
            var merchantAuthApiUrl = ConfigUtil.GetValue("MerchantAuthApiUrl");
            return await httpClient.GetAsync<MerchantModel>(merchantAuthApiUrl, paramsDic);
        }
    }
}